package com.xtx.interceptor;

import cn.dev33.satoken.stp.StpUtil;
import com.xtx.constant.JwtClaimsConstant;
import com.xtx.context.BaseContext;
import com.xtx.exception.UserNotLoginException;
import com.xtx.properties.JwtProperties;
import com.xtx.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

@Component
@Slf4j
public class JwtTokenUserInterceptor implements HandlerInterceptor {

    @Autowired
    private JwtProperties jwtProperties;
    /**
     * 校验jwt
     */
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler){
        //判断当前拦截到的是Controller的方法还是其他资源
        if (!(handler instanceof HandlerMethod)) {
            // 当前拦截的不是Controller中的方法，例如静态资源或特殊路径，直接放行
            return true;
        }
        //获取请求头中令牌
        String token = request.getHeader(jwtProperties.getUserTokenName());
        //校验令牌
        try {
            log.info("jwt校验开始"+ token);
            Claims claims = JwtUtil.parseJWT(jwtProperties.getUserSecretKey(), token);
            Long userId = Long.valueOf(claims.get(JwtClaimsConstant.USER_ID).toString());
            // 2. SaToken双重验证
            if (!StpUtil.isLogin()) {
                log.warn("用户未登录或会话已过期，用户ID: {}", userId);
                throw new UserNotLoginException("用户未登录或会话已过期");
            }
            log.info("当前用户id", userId);
            BaseContext.setCurrentId(userId);
            return true;
        } catch (Exception ex) {
            // 令牌校验失败，返回401并设置异常信息
            response.setStatus(401);
            throw new UserNotLoginException("用户未登录或令牌无效");
        }
    }


}
